<?php
/**
 * journalized log file
 *
 * This file is part of Webappkit, a packages system for PHP web apps
 * @link http://webappkit.net
 * @package webappkit
 * @subpackage fs
 * @author J.Ducastel <nospam0@ducastel.name>
 * @license http://opensource.org/licenses/gpl-license.php GNU Public License
 */

/**
 * @todo add line reading methods
 */
class WakLogFile extends WakTextFile {

    /**
     * factory : get a day's log instance
     * @param string $path logs folder
     * @param string $basename defaults to empty string (so file will be logs_folder/yyyy-mm-dd.log )
     * @param string $date date yyyy-mm-dd
     * @return WakLogFile
     */
    public static function getForDay($path, $basename='', $date=null) {
        if (!is_string($date))
            $date = date('Y-m-d');
        if (is_string($basename) and $basename)
            $path .= $basename.'.';
        return new WakLogFile($path.$date.'.log');
    }

    /* public methods, then properties */

    /**
     * add an entry line, separate lines by tabs
     * @param array $data fields data
     * @return bool
     */
    public function addEntry($data=array()) {
        // build line
        $line = $this->_buildLine($data);
        // write line
        return $this->_writeLogLine($line);
    }

    /**
     * read last entry
     */

    /* private methods, then properties */

    /**
     * write a line at the end of log
     * @param string $line
     * @return bool
     */
    protected function _writeLogLine($line) {
        return $this->toEnd()
        and $this->write($line)
        and $this->close();
    }

    /**
     * builds line from data (tab-separated)
     * @param array $data
     * @return string
     */
    protected function _buildLine($data=array()) {
        if (!is_array($data))
            throw new WakInvalidArgument("data should be an array");
        return implode(chr(9), $data).chr(13).chr(10);
    }
}